package com.mialab.jwbook.filterdemo.filter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

public class LogFilter implements Filter {
    private PrintWriter logger;
    private String prefix;

    public LogFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
        prefix = fConfig.getInitParameter("prefix");
        String logFileName = fConfig.getInitParameter("logFileName");
        String appPath = fConfig.getServletContext().getRealPath("/");
        // without path info in logFileName, the log file will be
        // created in $TOMCAT_HOME/bin

        System.out.println("logFileName:" + logFileName);
        try {
            logger = new PrintWriter(new File(appPath, logFileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("LogFilter.doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        logger.println(new Date() + " " + prefix + httpServletRequest.getRequestURI());
        logger.flush();
        filterChain.doFilter(request, response);
    }

    public void destroy() {
        System.out.println("destroying filter");
        if (logger != null) {
            logger.close();
        }
    }

}
